<?php
include "include/config.inc.php";
$today = date("Y-m-d");
$msg="";
$documentId = array();
$documentName = array();
$m=0;
$loanIdFind = "";
if(isset($_POST['loanBtn']))
{
  $installmentReceived = isset($_POST['installmentReceived']) && ($_POST['installmentReceived'] != "") ? $_POST['installmentReceived'] : 0 ;

  ///////////party Name Insert in party table from textbox Start
	if($_POST['partyNameSel'] == 0)
	{
	  $partyName = $_POST['partyName'];
	  $address   = $_POST['address'];
	  $city      = $_POST['city'];
	  $phone1    = $_POST['phone1'];
	  $phone2    = $_POST['phone2'];
	  if(isset($_POST['documents']))
	  {
      $documents     = implode(',',$_POST['documents']);
    }
  	else
  	{
      $documents     = "";
    }
  	$otherInfo = $_POST['otherInfo'];
    $insPartyTb = "INSERT INTO `party` (`partyName` ,`address` ,`city` ,`phone1` ,`phone2` ,`documentsId` ,`otherInfo`)
  	                            VALUES ('".$partyName."',  '".$address."',  '".$city."',  '".$phone1."',  '".$phone2."',  '".$documents."',  '".$otherInfo."')";
    $insPartyTbRes=mysql_query($insPartyTb);
  	$partyId = mysql_insert_id();
	}
	else
	{
	  $partyName = $_POST['partyName'];
  	$address   = $_POST['address'];
  	$city      = $_POST['city'];
  	$phone1    = $_POST['phone1'];
  	$phone2    = $_POST['phone2'];
    if(isset($_POST['documents']))
  	{
      $documents = implode(',',$_POST['documents']);
    }
    else
    {
      $documents = "";
    }
    $otherInfo = $_POST['otherInfo'];
    $updateParty = "UPDATE party 
                       SET partyName   = '".$partyName."',
                           address     = '".$address."',
  	                       city        = '".$city."',
  	                       phone1      = '".$phone1."',
  	                       phone2      = '".$phone2."',
  	                       documentsId = '".$documents."',
  	                       otherInfo   = '".$otherInfo."'
                     WHERE partyId     = ".$_POST['partyIdOld'];
    $updatePartyRes = mysql_query($updateParty);
    if(!empty($_POST['partyNameSel']))
	  {
      $partyId	= $_POST['partyNameSel'];	     	
    }
  }
///////////party Name Insert in party table from textbox Over  	
  $loanDate              = $_REQUEST['curDateYear']."-".$_REQUEST['curDateMonth']."-".$_REQUEST['curDateDay'];	
  $loadAmount            = $_POST['loadAmount'];	
  $loanInterest          = $_POST['loanInterest'];	
  $loanInstallmentAmount = $_POST['installmentAmount'];	
  $loanInstallmentDays   = $_POST['installmentDays'];	
///////////GuaranterId Insert in Party Table
  if(!empty($_POST['loanGuaranter']))
  {
    $loanGuaranter   = $_POST['loanGuaranter'];
    $insGuaranter="INSERT INTO  `party` (`partyName` ,`address` ,`city` ,`phone1` ,`phone2` ,`documentsId` ,`otherInfo`)
                   VALUES ('".$loanGuaranter."',  '',  '',  '".$_POST['guaranterPhone']."',  '',  '',  '".$_POST['guaranterOtherInfo']."')";
    $insGuaranterRes = mysql_query($insGuaranter);
    $selGuaranter    = "SELECT `partyId` 
                          FROM `party`
                         WHERE `partyName` = '".$loanGuaranter."'";
    $selGuaranterRes = mysql_query($selGuaranter);
    $selGuaranterResRow = mysql_fetch_array($selGuaranterRes);
    $loanGuaranterID = $selGuaranterResRow['partyId'];
  }
  else
  {
    if(!empty($_POST['loanGuaranterSel']))
    {
      $loanGuaranterID      = $_POST['loanGuaranterSel'];	
    }	
    else
    {
    	$loanGuaranterID = 0;
    }
  }
//loanId start
  if($_POST['loanId'] == "")
  {
  	//select max loanId :Start
    $selMaxLoanId="SELECT MAX(loanId) AS maxLoanId
                     FROM loan";
    $selMaxLoanIdRes=mysql_query($selMaxLoanId);
    $selMaxLoanIdResRow=mysql_fetch_array($selMaxLoanIdRes);
    $maxLoanId=$selMaxLoanIdResRow['maxLoanId'] + 1;      
    $loanId=$maxLoanId;    
    //select max loanId :End
  }
  else
  {
  	$selectChkDoublicte="SELECT loanId
  	                       FROM loan
  	                     WHERE  loanId=".$_POST['loanId'];
  	                     
   $selectChkDoublicteRes=mysql_query($selectChkDoublicte);
   
   $numRow=mysql_num_rows($selectChkDoublicteRes);	   
   
    if($numRow > 0)
    {
    	$msg="Your Loan Id is allready Exits";
    }
    else
    {
    	$loanId=$_POST['loanId'];
    }
  }
  
//loanId Over
///////////GuaranterId Insert in Party Table 
  if(empty($msg))
  {
    $insLoan="INSERT INTO  `loan` (`loanId`,`partyId` ,`loanDate` ,`loanAmount` ,`interest` ,`installmentAmount` ,`installmentDays` ,`guaranterId` ,`installmentReceived`)
                   VALUES (".$loanId.",
                           ".$partyId.",  
                           '".$loanDate."',  
                           ".$loadAmount.",  
                           ".$loanInterest.",  
                           ".$loanInstallmentAmount.",  
                           ".$loanInstallmentDays.",  
                           ".$loanGuaranterID.", 
                           ".$installmentReceived.")";
///////////Insert in Installment Table one by one date Start
    $insLoanRes=mysql_query($insLoan);
   
    $loanIdFind=$loanId;
    
    if($insLoanRes)
    {
      $loanId= $loanIdFind;
      $startDate= $loanDate;    	
      $loanInstallmentAmount;
      $loanInstallmentDays;
      $endDate=date('Y-m-d', strtotime($loanDate. ' + '.$loanInstallmentDays. 'day'));
      $nextDate = $startDate;
      $d=1;
      $installmentNo = 0;
      while(strtotime($nextDate) < strtotime($endDate))
      {
      	$installmentNo++;// aa oopar j raakhvoo... loop maa jaay etle 1 plus kari chhee
      	$isReceived = ($installmentNo <= $_POST['installmentReceived']) ? "Y" : "N";
      	$receiveDate = ($isReceived == "Y") ? $loanDate : "0000-00-00";
      	
        $insInstallment="INSERT INTO  `installment` (`loanId` , `installmentNo` ,`installmentDate` ,`installmentAmount` ,`isReceived`, receiveDate)
                         VALUES (".$loanId.",  ".$installmentNo.", '".$nextDate."',  ".$loanInstallmentAmount.",  '".$isReceived."', '".$receiveDate."')";
        $insInstallmentRes=mysql_query($insInstallment);
        $nextDate  = date ("Y-m-d", strtotime("+1 day", strtotime($nextDate)));
      }
    }
  }
///////////Insert in Installment Table one by one date Over
}
///////////fetch the party Name
$arrParty = array();
$i=0;
$selParty="SELECT `partyId`,`partyName` 
             FROM `party`
            ORDER BY partyName";
$selPartyRes=mysql_query($selParty);
while($selPartyResRow=mysql_fetch_array($selPartyRes))
{
  $arrParty['partyName'][$i] = $selPartyResRow['partyName'];
  $arrParty['partyId'][$i]   = $selPartyResRow['partyId'];
  $i++;
}
$selectDocument = "SELECT documentsId, document
                     FROM documents";
$selectDocumentRes = mysql_query($selectDocument);
while ($selectDocumentRow = mysql_fetch_array($selectDocumentRes))
{
  $documentId[$m]    = explode(',', $selectDocumentRow['documentsId']);
  $documentName[$m]  = explode(',', $selectDocumentRow['document']);
  $m++;
}
///////////fetch the party Name Over


$smarty->assign("documentId",$documentId);
$smarty->assign("loanIdFind",$loanIdFind);
$smarty->assign("documentName",$documentName);
$smarty->assign("today",$today);
$smarty->assign('arrParty',$arrParty);
$smarty->assign('msg',$msg);
$smarty->display('loan.tpl');  
?>